<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class OwnserviceModelTransactionall extends JModel
{
	/**
	 * Transactions data array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Transactions total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

	/**
	 * Transaction id
	 *
	 * @var int
	 */
	var $_id = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	 */

	function __construct()
	{
		parent::__construct();
		
		global $mainframe, $option;
		
		//get the number of entries from session
		$limit			= $mainframe->getUserStateFromRequest($option.'.transactionall.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');		
		$limitstart		= $mainframe->getUserStateFromRequest($option.'.transactionall.limitstart', 'limitstart', 0, 'int' );
		
		$limitstart 	= ( $limit != 0 ? (floor($limitstart / $limit) * $limit) : 0 );
		
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}

	/**
	 * Method to set the Transaction identifier
	 *
	 * @access	public
	 * @param	int Category identifier
	 */
	function setId($id)
	{
		// Set id and wipe data
		$this->_id	 = $id;
		$this->_data = null;
	}
	
	/**
	 * Method to get Data
	 *
	 * @access public
	 * @return mixed
	 */
	function getData()
	{
		// Lets load the transaction if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			//echo $query;
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_data;
	}
	
	
	/**
	 * Total nr of Today transaction
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		// Lets load the total nr if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the members
	 *
	 * @access public
	 * @return object
	 */
	function getPagination() {

		// Lets load the customer account if it doesn't already exist
		if (empty($this->_pagination)) {
			jimport('joomla.html.pagination');
			$this->_pagination = new FMCPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}
	
	/**
	 * Builds the query
	 *
	 * @access public
	 * @return string
	 */
	function _buildQuery() {
		
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildItemWhere();
		$orderby	= $this->_buildItemOrderBy();
		
		$query = ' SELECT t.*, u.username, u.name, p.id AS memberid, '
				.' tf.name AS transferer, '
				.' a.account_name, a.bank_name, a.bank_other, a.branch_city, c.iscore, c.code AS currencycode '
				.' FROM #__ownservice_transactions AS t '
				.' LEFT JOIN #__users AS u ON u.id=t.user_id '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' LEFT JOIN #__users AS tf ON tf.id=t.transfer_id '
				.' LEFT JOIN #__ownservice_accounts AS a ON a.account_no = t.account '
				.' LEFT JOIN #__ownservice_exchangerates AS e ON e.id=t.rate_id '
				.' LEFT JOIN #__ownservice_currencies AS c ON c.id=e.currency_id '
				. $where
				.' GROUP BY t.id '
				. $orderby
				;
				
				
		return $query;
	}
	
	/**
	 * Build the order clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildItemOrderBy()
	{
		global $mainframe, $option;
		
		$filter_order		= $mainframe->getUserStateFromRequest($option.'.transactionall.filter_order', 'filter_order', 't.created', 'cmd');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest($option.'.transactionall.filter_order_Dir', 'filter_order_Dir', 'DESC', 'cmd');
		
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_dir.', t.created';

		return $orderby;
	}
	
	/**
	 * Method to build the WHERE clause
	 *
	 * @access private
	 * @return array
	 */
	function _buildItemWhere( )
	{
		global $mainframe, $option;
		
		$filter_date			= $mainframe->getUserStateFromRequest($option.'.transactionall.date','date','','string' );
		$filter_status		= $mainframe->getUserStateFromRequest($option.'.transactionall.filter_status','filter_status',0,'int' );
		$filter_branch		= $mainframe->getUserStateFromRequest($option.'.transactionall.filter_branch','filter_branch',0,'int' );
		$search				= $mainframe->getUserStateFromRequest($option.'.transactionall.search', 'search', '', 'string' );
		if (strpos($search, '"') !== false) {
			$search = str_replace(array('=', '<'), '', $search);
		}
		$search = JString::strtolower($search);
		
		$where		= array();
		
		//filter date
		if($filter_date != '')
		{
			$where[]		= '(t.created >= '.$this->_db->Quote($filter_date.' 00:00:00').' AND t.created <= '.$this->_db->Quote($filter_date.' 23:59:59').')';
		}

		//filter status
		if($filter_status)
		{
			$where[] = 't.state ='.(int) $filter_status;
		}

		//filter branch
		if($filter_branch)
		{
			$where[] = 't.branch_id='.$filter_branch;	
		}

		//filter search
		if($search) {
			$text		= $this->_db->Quote('%'.$this->_db->getEscaped($search, true).'%', false);

			$wheres2	= array();
			$wheres2[]	= 't.invoice LIKE '.$text;
			$wheres2[]	= 't.account LIKE '.$text;
			$wheres2[]	= 'u.username LIKE '.$text;
			$where[]		= '((' . implode(') OR (', $wheres2) . '))';
		}

		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );
		if (count( $cid ))
		{
			$where[] = 't.id IN ('.implode( ',', $cid ).')';
		}
		
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
		
		return $where;
		
	}

	/**
	 * Method to remove transactions
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.0
	 */
	function delete($cid = array())
	{
		$result = false;

		if (count( $cid ))
		{
			$cids = implode( ',', $cid );

			$query = 'DELETE FROM #__ownservice_transactions '
						. ' WHERE id IN ('. $cids .')';

			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

	/**
	 * Method to get Branches list
	 * 
	 * @access public
	 * @return array object
	 * @since 1.5
	 */
	function getBranches(){

		$query = 'SELECT * FROM #__ownservice_branches  '
				.' WHERE deleted=0 AND published = 1'
				.' ORDER BY name';

		$this->_db->setQuery($query);
		$branches = $this->_db->loadObjectList();

		return $branches;
	}
}